package at.fhj.itm11.fotorater.rest;

import javax.faces.bean.RequestScoped;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;

import org.jboss.resteasy.annotations.providers.multipart.MultipartForm;

import at.fhj.itm11.fotorater.controller.PhotoUploadController;
import at.fhj.itm11.fotorater.data.CategoryRepository;
import at.fhj.itm11.fotorater.service.PhotoUploadService;
import at.fhj.itm11.fotorater.util.PhotoUploader;

@Path("/upload")
@RequestScoped
public class PhotoUploadRESTService {

	@Inject
	private CategoryRepository catRepo;

	@Inject
	private PhotoUploader uploader;

	@Inject
	private PhotoUploadService photoService;

	@POST
	@Consumes("multipart/form-data")
	public Response uploadFile(@MultipartForm PhotoUploadController photoCtr) {

		String filePath;
		try {
			filePath = uploader.uploadAndCreateThumbnail(photoCtr.getData(),
					photoCtr.getFileType());

			photoService.upload(photoCtr.getName(), filePath,
					photoCtr.getCategory());

			return Response.status(200).entity("Uploaded.").build();
		} catch (Exception e) {
			e.printStackTrace();
			return Response.status(500).entity("Upload failed.").build();
		}
	}
}
